package com.nantai.jiafang.nantaijiafang.zhijian.activity;

import android.app.DatePickerDialog;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.MultiAutoCompleteTextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nantai.jiafang.nantaijiafang.Data;
import com.nantai.jiafang.nantaijiafang.R;
import com.nantai.jiafang.nantaijiafang.ViewModel.Zhijian_Net;
import com.nantai.jiafang.nantaijiafang.activity.adapter.FilterAdapter;
import com.nantai.jiafang.nantaijiafang.activity.adapter.SectionsPagerAdapter2;
import com.nantai.jiafang.nantaijiafang.base.BaseActivity;
import com.nantai.jiafang.nantaijiafang.bean.ReCheckBean;
import com.nantai.jiafang.nantaijiafang.bean.ZhiJjian.HeTongHao;
import com.nantai.jiafang.nantaijiafang.bean.ZhiJjian.MLHeardItem;
import com.nantai.jiafang.nantaijiafang.bean.ZhiJjian.Tip;
import com.nantai.jiafang.nantaijiafang.databinding.ActivityZhiJianBinding;
import com.nantai.jiafang.nantaijiafang.zhijian.fragment.Pager_Fragment;
import com.nantai.jiafang.nantaijiafang.zhijian.fragment.ZhijianFragment_add;

import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ZhiJianActivity extends BaseActivity<ActivityZhiJianBinding> implements View.OnClickListener {
    private ActivityZhiJianBinding binding;
    private FilterAdapter<String> arrayAdapter, arrayAdapter2;
    private ArrayList<String> lists, lists2;
    private SectionsPagerAdapter2 pagerAdapter;
    private MLHeardItem mlHeardItemList;

    private int numitem = 5;
    private int selectpage, type;
    private ArrayList<Boolean> flag;
    private ArrayList<Pager_Fragment> fragmentArrayList = new ArrayList<>();
    private Map<String, String> maps = null;
    private List<HeTongHao> heTongHaos;
    private List<Integer> post;
    private Calendar calendar = Calendar.getInstance();

    @Override
    public int layoutid() {
        return R.layout.activity_zhi_jian;
    }

    @Override
    public void init(ActivityZhiJianBinding binding) {
        this.binding = binding;
        final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_zhijian);
        toolbar.setContentInsetStartWithNavigation(0);
        //设置导航按钮的点击事件
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        type = getIntent().getIntExtra("type", 0);
        if (type == 0) {
            binding.bt5.setVisibility(View.GONE);
            binding.bt6.setVisibility(View.GONE);
        } else {
            binding.bt0.setVisibility(View.GONE);
            binding.bt6.setVisibility(View.GONE);
        }
        if (type == 1) {
            binding.bt10.setVisibility(View.VISIBLE);
        }
        getdata();
        binding.setOnclicklistener(this);
        binding.autoTvHetong.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
        binding.autoTvMianliao.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
        binding.editJianyanyuan.setText(Data.ZHIJIAN_Account);
        initUI();
        post = new ArrayList<>();
        binding.autoTvMianliao.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                post.add(arrayAdapter2.getMposition(position));
            }
        });
        binding.autoTvMianliao.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(binding.autoTvMianliao.getText())) {
                    post.clear();
                } else {
                    int index = binding.autoTvMianliao.getText().toString().lastIndexOf(", ");
                    if (index <= 0) {
                        post.clear();
                    } else {
                        String str = binding.autoTvMianliao.getText().toString().substring(0, index);
                        int n = str.split(", ").length;
                        n = post.size() - n;
                        for (int i = n; i > 0; i--) {
                            post.remove(i);
                        }
                    }
                }

            }
        });
    }

    private void initUI() {
//        String year =String.valueOf(calendar.get(Calendar.YEAR)) ;//年份
//        String month =String.valueOf( calendar.get(Calendar.MONTH)+1); //月份
//        String date =String.valueOf( calendar.get(Calendar.DATE));//日期
//        if (Integer.valueOf(month)<10){
//            month=String.valueOf(Integer.valueOf(month)+1);
//        }
//        if (Integer.valueOf(date)<10){
//            month=String.valueOf(Integer.valueOf(date)+1);
//        }
        String datetime = "";
        binding.DateTime.setText(datetime);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_10:
                try {
                    String guid10 = fragmentArrayList.get(selectpage).zhiJianAdapter.getGuid();
                    if (guid10.length() < 1) {
                        toast("请选择复检项");
                        return;
                    }
                    Log.e("xu_xin", "guid10 = " + guid10);
                    reCheck2(guid10);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.bt_0:
                getSupportFragmentManager().beginTransaction()
                        .addToBackStack(null)
                        .setCustomAnimations(R.anim.in_from_left, R.anim.in_from_right, R.anim.out_from_left, R.anim.out_from_right)
                        .add(R.id.container2, new ZhijianFragment_add())
                        .commit();
                break;
            case R.id.bt_1:
                try {
                    String guid = fragmentArrayList.get(selectpage).zhiJianAdapter.getGuid();
                    if (guid.length() < 1)
                        return;
                    onApprove(guid, selectpage, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.bt_2:
                try {
                    String guid2 = fragmentArrayList.get(selectpage).zhiJianAdapter.getGuid();
                    if (guid2.length() < 1)
                        return;
                    onApprove(guid2, selectpage, false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.bt_3:
                try {
                    flag = fragmentArrayList.get(selectpage).zhiJianAdapter.getFlag();
                    String guid3 = fragmentArrayList.get(selectpage).zhiJianAdapter.getGuid();
                    if (guid3.length() < 1)
                        return;
                    deleteguid(guid3, selectpage, flag);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.bt_4:
                try {
                    String s;
                    if (TextUtils.isEmpty(binding.autoTvHetong.getText().toString())) {
                        s = "  ";
                    } else {
                        s = "\'" + binding.autoTvHetong.getText().toString().replace(", ", "\',\'");
                    }
                    StringBuffer s2 = new StringBuffer();
                    s2.append("");
                    for (int i = 0; i < post.size(); i++) {
                        s2.append("'" + heTongHaos.get(post.get(i)).getValue() + "',");
                    }
                    if (s2.length() > 0) {
                        s2.deleteCharAt(s2.length() - 1);
                    }
                    maps = new HashMap<>();
                    maps.put("opType", "getEInspectHead");
                    maps.put("ContractNo", s.substring(0, s.length() - 2));
                    maps.put("FabricCodes", s2.toString());
                    maps.put("SupplierName", binding.editGongyishang.getText().toString()); //供应商
                    maps.put("InspectorName", binding.editJianyanyuan.getText().toString()); //检验员
                    maps.put("ShowUnApprove", binding.checkNo.isChecked() ? "1" : "0");
                    maps.put("Type", type == 0 ? "合格" : "不合格");
                    maps.put("PageIndex", binding.editPage.getText().toString());
                    maps.put("PageCount", String.valueOf(numitem));
                    maps.put("InspectorTime", binding.DateTime.getText().toString());
                    maps.put("SamplingNo", binding.simplingNo.getText().toString());
                    maps.put("OffID", binding.OffId.getText().toString());
                    getHeardItem(maps);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.bt_5:
                try {
                    String guid5 = fragmentArrayList.get(selectpage).zhiJianAdapter.getGuid();
                    if (guid5.length() < 1)
                        return;
                    admitPass(guid5);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.bt_6:
                try {
                    String guid6 = fragmentArrayList.get(selectpage).zhiJianAdapter.getGuid();
                    if (guid6.length() < 1)
                        return;
                    reCheck(guid6);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.check_no:
                try {
                    if (maps != null) {
                        maps.put("ShowUnApprove", binding.checkNo.isChecked() ? "未审核" : "审核");
                        getHeardItem(maps);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.img_search:
                try {
                    if (Integer.valueOf(binding.editPage.getText().toString()) == 0) {
                        return;
                    }
                    binding.viewpager.setCurrentItem(Integer.valueOf(binding.editPage.getText().toString()) - 1);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.DateTime:
                try {
                    DatePickerDialog dpd = new DatePickerDialog(this, Datelistener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                    dpd.show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void reCheck2(String guid) {
        Log.e("xu_xin", "reCheck2");
        RequestParams params = new RequestParams("http://58.214.250.250:5500/QAHandler.ashx?opType=reCheck");
        params.addBodyParameter("type", "重新检验");
        params.addBodyParameter("UserName", Data.ZHIJIAN_Account);
        params.addBodyParameter("Guid", guid);
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                try {
                    Gson gson = new Gson();
                    List<ReCheckBean> list = gson.fromJson(result, new TypeToken<List<ReCheckBean>>() {
                    }.getType());
                    toast(list.get(0).getTip());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable throwable, boolean b) {
                LogUtil.e("onError");
            }

            @Override
            public void onCancelled(CancelledException e) {
                LogUtil.e("onCancelled");
            }

            @Override
            public void onFinished() {
                LogUtil.e("onFinished");
            }
        });
    }

    private void getdata() {
        Zhijian_Net.gethetonghao(this.getApplicationContext(), new Zhijian_Net.GetDoubleData() {
            @Override
            public void success(Object s) {
                lists = (ArrayList<String>) s;
                Data.hetonghao = lists;
                arrayAdapter = new FilterAdapter<String>(ZhiJianActivity.this.getApplication(), lists);
                binding.autoTvHetong.setAdapter(arrayAdapter);
            }

            @Override
            public void success2(Object s) {
                ArrayList<String> listt = new ArrayList<>();
                heTongHaos = (List<HeTongHao>) s;
                for (HeTongHao heTongHao :
                        heTongHaos) {
                    listt.add(heTongHao.getText());
                    // listt2.add(heTongHao.getValue());
                }
                arrayAdapter2 = new FilterAdapter<String>(ZhiJianActivity.this.getApplication(), listt);
                binding.autoTvMianliao.setAdapter(arrayAdapter2);
            }
        });
    }

    private void getHeardItem(Map<String, String> maps) {
        Zhijian_Net.getHeardItem(this.getApplicationContext(), maps, new Zhijian_Net.GetSingData() {
            @Override
            public void success(Object s) {
                mlHeardItemList = (MLHeardItem) s;
                setHeardItemUI(maps, mlHeardItemList.getCountNo().get(0).getTotalCount());
            }
        });
    }

    private DatePickerDialog.OnDateSetListener Datelistener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {
            String month = "";
            String day = "";
            if (monthOfYear < 9) {
                month = "0" + (monthOfYear + 1);
            } else {
                month = "" + (monthOfYear + 1);
            }
            if (dayOfMonth < 10) {
                day = "0" + dayOfMonth;
            } else {
                day = "" + dayOfMonth;
            }
            binding.DateTime.setText(myyear + "-" + month + "-" + day);
        }
    };

    /**
     * 分页
     */
    private void setHeardItemUI(Map<String, String> maps, String count) {
        fragmentArrayList.clear();
        int nn = Integer.valueOf(count);
        int n_page = nn / numitem;
        if (nn % numitem != 0) {
            n_page++;
        }
        FragmentManager _fragmentManager = getSupportFragmentManager();

        if (_fragmentManager != null) {
            FragmentTransaction ft = _fragmentManager.beginTransaction();
            for (Fragment f : _fragmentManager.getFragments()) {
                ft.remove(f);
            }
            ft.commit();
            ft = null;
            _fragmentManager.executePendingTransactions();
        }
//        Log.e("dsfasdf", "n_page: "+maps.size() );
//        Log.e("dsfasdf", "count: "+count );


        binding.tvSumpagers.setText("共 " + n_page + " 页");
        Log.e("_______________", "getHeardItem2: ");
//        for (int i = 1; i <=n_page ; i++) {
//            maps.put("PageIndex",String.valueOf(i));
//            Map<String,String> mapp=new HashMap<>();
//            mapp.putAll(maps);
//
//            fragmentArrayList.add(Pager_Fragment.initdata(mapp,_fragmentManager));
//        }
        Map<String, String> mapp = new HashMap<>();
        mapp.putAll(maps);

        fragmentArrayList.add(Pager_Fragment.initdata(mapp, _fragmentManager));
        Log.e("dsfasdf", "count: " + count);
        if (pagerAdapter != null) {
            pagerAdapter.setPager_fragments(fragmentArrayList);
            for (Pager_Fragment pager_fragment : fragmentArrayList) {
                pager_fragment.setfragmentmanager(_fragmentManager);
            }
        } else {
            pagerAdapter = new SectionsPagerAdapter2(getApplicationContext(), _fragmentManager, fragmentArrayList);
            binding.viewpager.setAdapter(pagerAdapter);
            binding.editPage.setText("" + 1);
            for (Pager_Fragment pager_fragment : fragmentArrayList) {
                pager_fragment.setfragmentmanager(_fragmentManager);
            }
        }


        //pagerAdapter.notifyDataSetChanged();
//        pagerAdapter= new SectionsPagerAdapter2(this.getApplicationContext(),getSupportFragmentManager(),fragmentArrayList);
//        binding.viewpager.setAdapter(pagerAdapter);
        binding.viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                selectpage = position;
                binding.editPage.setText(String.valueOf(position + 1));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void deleteguid(String guid, final int selectpage, final ArrayList<Boolean> flag) {
        Map<String, String> maps = new HashMap<>();
        maps.put("opType", "batchDeleteHead");
        maps.put("Guids", guid);
        Zhijian_Net.batchDeletehead(this.getApplicationContext(), maps, new Zhijian_Net.GetSingData<List<Tip>>() {
            @Override
            public void success(List<Tip> s) {
                for (int i = 0; i < flag.size(); i++) {
                    if (flag.get(i)) {
                        // flag.remove(i);
                        fragmentArrayList.get(selectpage).zhiJianAdapter.removeitem(i);
                        i--;
                    }
                }
                toast(s.get(0).getTip());
            }
        });
    }

    private void onApprove(String guid, final int selectpage, final boolean isApprove) {
        String approve = "未审核";
        if (isApprove) {
            approve = "审核";
        } else {
            approve = "未审核";
        }
        Map<String, String> maps = new HashMap<>();
        maps.put("opType", "opApprove");
        maps.put("type", approve);
        maps.put("UserName", Data.ZHIJIAN_Account);
        maps.put("Guid", guid);
        Zhijian_Net.opApprove(this.getApplicationContext(), maps, new Zhijian_Net.GetSingData<List<Tip>>() {
            @Override
            public void success(List<Tip> s) {
                fragmentArrayList.get(selectpage).zhiJianAdapter.onApproveitem(isApprove);
                toast(s.get(0).getTip());
            }
        });
    }


    /**
     * 准入
     *
     * @param guid
     */
    private void admitPass(String guid) {
        Map<String, String> maps = new HashMap<>();
        maps.put("UserName", Data.ZHIJIAN_Account);
        maps.put("Guid", guid);
        Zhijian_Net.admitPass(this.getApplicationContext(), maps, new Zhijian_Net.GetSingData<List<Tip>>() {
            @Override
            public void success(List<Tip> s) {
                Toast.makeText(ZhiJianActivity.this, s.get(0).getTip(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 重新检验
     *
     * @param guid
     */
    private void reCheck(String guid) {
        Map<String, String> maps = new HashMap<>();
        maps.put("UserName", Data.ZHIJIAN_Account);
        maps.put("Guid", guid);
        Toast.makeText(this, guid, Toast.LENGTH_SHORT).show();
        Zhijian_Net.reCheck(this.getApplicationContext(), maps, new Zhijian_Net.GetSingData<List<Tip>>() {
            @Override
            public void success(List<Tip> s) {
                Toast.makeText(ZhiJianActivity.this, s.get(0).getTip(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (maps != null)
            getHeardItem(maps);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("______", "onDestroy: ");
    }
}
